Imports DotNetPM.Business.Questionnaire
Imports DotNetPM.Business.Questionnaire.UserControls
Imports System.Xml

Partial Class Modules_InstrumentLogic
    Inherits baseWebPage

#Region "Protected"

    Protected Function TranslateLogic(ByVal logic As String) As String
        If String.IsNullOrEmpty(logic) Then
            Return String.Empty
        End If
        Dim val As String() = logic.Split("|")
        Dim sbAns As New StringBuilder
        Dim ans As String = String.Empty
        If val(3) = "-1" Then
            Return "No condition"
        End If
        Select Case val(0)
            Case "1"    ' Date
                Select Case val(3)
                    Case "0"    'Specific date
                        sbAns.Append("When the selected date ")
                    Case "1"    'Cover the specific date
                        sbAns.Append("When the date range covers ")
                    Case "2"    'Not cover the specific date
                        sbAns.Append("When the date range doesn't cover ")
                    Case "3"    'Number of days in range
                        sbAns.Append("When the number of days in range ")
                    Case "4"    'Lower Date
                        sbAns.Append("When the lower date range ")
                    Case "5"    'Upper Date
                        sbAns.Append("When the upper date range ")
                    Case Else
                        sbAns.Append("Invalid date ")
                End Select
                ans = """" & val(2) & """"
            Case "2"    ' Float
                sbAns.Append("When the answer of float ")
                ans = """" & val(2) & """"
            Case "3"    ' Integer
                sbAns.Append("When the answer of integer ")
                ans = """" & val(2) & """"
            Case "4"    ' MCMA
                If val(3) = "0" Then
                    'Individual Answer
                    sbAns.Append("When the selected answer ")
                    ans = """" & TranslateMCSA(val(2)) & """"
                Else
                    'Number of selected answers
                    sbAns.Append("When the number selected answers ")
                    ans = """" & val(2) & """"
                End If
            Case "5"    ' MCSA
                sbAns.Append("When the selected answer ")
                ans = """" & TranslateMCSA(val(2)) & """"
            Case "6"    ' Text
                If val(3) = "0" Then
                    'Individual Answer
                    sbAns.Append("When the answer contains ")
                Else
                    'Number of selected answers
                    sbAns.Append("When the length of the answer ")
                    ans = """" & val(2) & """"
                End If
                ans = """" & val(2) & """"
            Case "7"    ' Time
                Select Case val(3)
                    Case "0"    'Specific time
                        sbAns.Append("When the selected time ")
                    Case "1"    'Cover the specific time
                        sbAns.Append("When the time range covers ")
                    Case "2"    'Not cover the specific time
                        sbAns.Append("When the time range doesn't cover ")
                    Case "3"    'Number of hours in range
                        sbAns.Append("When number of hours in the range ")
                    Case "4"    'Lower time
                        sbAns.Append("When the lower time range ")
                    Case "5"    'Upper time
                        sbAns.Append("When the upper time range ")
                    Case Else
                        sbAns.Append("Invalid time ")
                End Select
                ans = """" & val(2) & """"
        End Select
        sbAns.Append(TranslateOperator(val(1)))
        sbAns.Append(ans)
        sbAns.Append(".")
        Return sbAns.ToString
    End Function

    Protected Function GetQuestion(ByVal QuestionID As Integer) As String
        Dim question As Question = QuestionODS.GetQuestion(QuestionID)
        If Len(question.Question) > 100 Then
            Return question.Question.Substring(0, 96) & " ..."
        Else
            Return question.Question
        End If
    End Function

#End Region

#Region "Private"

    Dim _logic As Logic
    Dim _uc As UserControl

    Private Sub LoadLogicControl()
        If _uc Is Nothing Then
            Dim question As Question
            Dim currentGUID As String = Session("questionnaire_currentGuid")
            If String.IsNullOrEmpty(currentGUID) Then
                ' Session is expired.
                Response.Redirect("InstrumentManager.aspx")
            End If
            _logic = New Logic(currentGUID)
            If _logic.QuestionID < 0 Then
                ' It happens when there is no QuestionID in the Questionnaires_Logics table.
                question = QuestionODS.GetQuestion(Session("questionnaire_questionId"))
            Else
                question = QuestionODS.GetQuestion(_logic.QuestionID)
            End If
            'Response.Write("guid = " & _logic.UID & "<br/>")
            'Response.Write("parent guid = " & _logic.ParentUID & "<br/>")
            lblQuestion.Text = question.Question
            Dim type As String = question.Configuration.Substring(0, 1)
            Dim myXML As XmlDocument = ControlXDS.GetXmlDocument
            Dim myNode As XmlNode = myXML.SelectSingleNode("/controlList/control[@id=" & type & "]")
            _uc = LoadControl(ResolveUrl("~/Secure/Controls/log" & myNode.Attributes("control").Value))
            _uc.ID = "logUC"
            CType(_uc, ILogicUC).Question = question
            phLoader.Controls.Add(_uc)
        End If
    End Sub

    Private Function TranslateOperator(ByVal op As String) As String
        Select Case op
            Case "0"    '=
                Return "is equal to "
            Case "1"    '<>
                Return "is not equal to "
            Case "2"    '>
                Return "is more than "
            Case "3"    '>=
                Return "is more than or equal to "
            Case "4"    '<
                Return "is less than "
            Case "5"    '<=
                Return "is less than equal to "
            Case Else
                Return String.Empty
        End Select
    End Function

    Private Function TranslateMCMA(ByVal ans As String) As String
        Dim dt As Data.DataTable = QuestionODS.GetChoices(CType(_uc, ILogicUC).Question.ID)
        Dim anss As String() = ans.Split(",")
        Dim _ans As String = String.Empty
        Dim _first As Boolean = True
        For Each str As String In anss
            Dim dr As Data.DataRow = dt.Select("SortID=" & ans)(0)
            If _first Then
                _ans &= dr.Item(2)
                _first = False
            Else
                _ans &= "," & dr.Item(2)
            End If
        Next
        Return _ans
    End Function

    Private Function TranslateMCSA(ByVal ans As String) As String
        Dim dt As Data.DataTable = QuestionODS.GetChoices(CType(_uc, ILogicUC).Question.ID)
        Dim dr As Data.DataRow = dt.Select("SortID=" & ans)(0)
        Return dr.Item(2).ToString
    End Function

    Private Sub NavigateBack()
        If String.IsNullOrEmpty(_logic.ParentUID) Then
            Response.Redirect("InstrumentDetail.aspx")
        Else
            Session("questionnaire_logicLevel") -= 1
            Session("questionnaire_currentGuid") = _logic.ParentUID
            Response.Redirect("InstrumentLogic.aspx")
        End If
    End Sub

#End Region

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        LoadLogicControl()
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            'Response.Write("Not IsPostBack")
            SetState()
        End If
        If Not String.IsNullOrEmpty(Request.QueryString("questionId")) Then
            'AddEditVisible(True, True)
            lstQuestions.SelectedValue = Request.QueryString("questionId")
        End If
        lblLevel.Text = "Level " & Session("questionnaire_logicLevel")
    End Sub

    Protected Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete
        lbutNew.Visible = IsNotLocked()
        'Response.Write("Page_PreRenderComplete : " & (ViewState("IsNotLocked")) & "<br/>")
    End Sub

    Protected Function IsNotLocked() As Boolean
        Return CType(ViewState("IsNotLocked"), Boolean)
    End Function

    Protected Sub lbBack_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbBack.Click
        NavigateBack()
    End Sub

    Protected Sub gvLogics_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvLogics.RowCommand
        'Response.Write(e.CommandArgument & "<br/>")
        Select Case e.CommandName
            Case "EditLogic"
                ' Convert the row index stored in the CommandArgument
                ' property to an Integer.
                Dim index As Integer = Convert.ToInt32(e.CommandArgument) _
                    - gvLogics.PageIndex * gvLogics.PageSize
                ' Retrieve the row that contains the button clicked 
                ' by the user from the Rows collection.
                Dim row As GridViewRow = gvLogics.Rows(index)
                'Set current from the UID of the table
                Session("questionnaire_logicLevel") += 1
                Session("questionnaire_currentGuid") = CType(row.FindControl("hfUID"), HiddenField).Value
                Response.Redirect("InstrumentLogic.aspx")
            Case "SelectLogic"
                With gvLogics
                    Dim index As Integer = Convert.ToInt32(e.CommandArgument) _
                        - .PageIndex * .PageSize
                    ' Retrieve the row that contains the button clicked 
                    ' by the user from the Rows collection.
                    .SelectedIndex = index
                    Dim row As GridViewRow = .SelectedRow
                    AddEditVisible(True, False)
                    CType(_uc, ILogicUC).Logic = CType(row.FindControl("hfLogic"), HiddenField).Value
                    lstQuestions.Enabled = CBool(CType(row.FindControl("hfEnable"), HiddenField).Value)
                    ddlCategories.Enabled = lstQuestions.Enabled
                    lbutCreate.Enabled = lstQuestions.Enabled
                    txtStringToSearch.Enabled = lstQuestions.Enabled
                    butSearch.Enabled = lstQuestions.Enabled
                    butClear.Enabled = lstQuestions.Enabled
                    'Response.Write("Logic = " & CType(row.FindControl("hfLogic"), HiddenField).Value)
                    lstQuestions.SelectedValue = CType(row.FindControl("hfQuestionID"), HiddenField).Value
                End With
        End Select
    End Sub


    'Protected Sub gvLogics_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvLogics.SelectedIndexChanged
    '    'Response.Write(ddlCategories.SelectedIndex & " - gvLogics_SelectedIndexChanged <br/>")
    '    With gvLogics
    '        If .SelectedIndex > -1 Then
    '            AddEditVisible(True, False)
    '            Dim row As GridViewRow = .Rows(.SelectedIndex)
    '            CType(_uc, ILogicUC).Logic = CType(row.FindControl("hfLogic"), HiddenField).Value
    '            lstQuestions.Enabled = CBool(CType(row.FindControl("hfEnable"), HiddenField).Value)
    '            ddlCategories.Enabled = lstQuestions.Enabled
    '            lbutCreate.Enabled = lstQuestions.Enabled
    '            txtStringToSearch.Enabled = lstQuestions.Enabled
    '            butSearch.Enabled = lstQuestions.Enabled
    '            butClear.Enabled = lstQuestions.Enabled
    '            'Response.Write("Logic = " & CType(row.FindControl("hfLogic"), HiddenField).Value)
    '            lstQuestions.SelectedValue = CType(row.FindControl("hfQuestionID"), HiddenField).Value
    '        End If
    '    End With
    'End Sub


    Private Sub AddEditVisible(ByVal visible As Boolean, ByVal AddingMode As Boolean)
        trEdit.Visible = visible
        lbutNew.Enabled = Not visible
        ibutBack.Visible = Not visible
        If visible Then
            If AddingMode Then
                CType(_uc, ILogicUC).Reset()
                butUpdate.Visible = False
                butAdd.Visible = True
                lstQuestions.Enabled = True
                ddlCategories.Enabled = True
                txtStringToSearch.Enabled = True
                butSearch.Enabled = True
                butClear.Enabled = True
                tdAddEdit.InnerHtml = "<strong>Adding :</strong>"
            Else
                ibutTop.Visible = True
                butUpdate.Visible = True
                butAdd.Visible = False
                ddlCategories.SelectedIndex = 0
                tdAddEdit.InnerHtml = "<strong>Editing :</strong>"
            End If
        Else
            ibutTop.Visible = False
            gvLogics.SelectedIndex = -1
            lstQuestions.SelectedIndex = -1
        End If
        ibutUp.Visible = ibutTop.Visible
        ibutDown.Visible = ibutTop.Visible
        ibutButtom.Visible = ibutTop.Visible
    End Sub

    Protected Sub butAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butAdd.Click
        InstrumentODS.AddInstrumentLogic(_logic.UID, lstQuestions.SelectedValue, CType(_uc, ILogicUC).Logic)
        gvLogics.DataBind()
        AddEditVisible(False, True)
    End Sub

    Protected Sub butUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butUpdate.Click
        Dim row As GridViewRow = gvLogics.Rows(gvLogics.SelectedIndex)
        Dim uid As String
        uid = CType(row.FindControl("hfUID"), HiddenField).Value
        'Response.Write("UID = " & uid & "<br/>")
        'Response.Write("QuestionID = " & lstQuestions.SelectedValue & "<br/>")
        'Response.Write("Logic = " & CType(_uc, ILogicUC).Logic & "<br/>")
        InstrumentODS.UpdateInstrumentLogic( _
            CType(row.FindControl("hfUID"), HiddenField).Value, _
            lstQuestions.SelectedValue, CType(_uc, ILogicUC).Logic)
        gvLogics.DataBind()
        AddEditVisible(False, True)
    End Sub

    Protected Sub butCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butCancel.Click
        AddEditVisible(False, True)
        gvLogics.SelectedIndex = -1
        lstQuestions.SelectedIndex = -1
        ibutBack.Focus()
    End Sub

    Protected Sub ibutBack_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ibutBack.Click
        NavigateBack()
    End Sub

    Protected Sub lbutNew_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbutNew.Click
        AddEditVisible(True, True)
        lstQuestions.Enabled = True
        ddlCategories.Enabled = lstQuestions.Enabled
        lbutCreate.Enabled = lstQuestions.Enabled
        txtStringToSearch.Enabled = lstQuestions.Enabled
        butSearch.Enabled = lstQuestions.Enabled
        butClear.Enabled = lstQuestions.Enabled
    End Sub

    Protected Sub lbutCreate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbutCreate.Click
        MyBase.SetPreviousPage(GetState)
        Response.Redirect("QuestionCreate.aspx")
    End Sub


#Region "Search Question"

    Protected Sub butSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butSearch.Click
        Session("questionnaire_category") = ddlCategories.SelectedValue
    End Sub

    Protected Sub butClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butClear.Click
        ddlCategories.SelectedIndex = 0
        Session("questionnaire_category") = 0
        txtStringToSearch.Text = String.Empty
    End Sub

    Protected Sub ddlCategories_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlCategories.DataBound
        'Response.Write("ddlCategories_DataBound<br/>")
        ddlCategories.SelectedValue = Session("questionnaire_category")
    End Sub

#End Region

    Private Function GetState() As String
        Dim state As String = "prevstate="
        state &= gvLogics.SelectedIndex
        state &= "$"
        state &= gvLogics.PageIndex
        state &= "$"
        state &= lstQuestions.SelectedValue
        state &= "$"
        state &= lstQuestions.Enabled
        state &= "$"
        state &= CType(_uc, ILogicUC).Logic
        state &= "#editarea"
        Return state
    End Function

    Private Sub SetState()
        Dim queryString As String = Request.QueryString("prevstate")
        If String.IsNullOrEmpty(queryString) Then
            Exit Sub
        End If
        'Response.Write(Server.HtmlDecode(queryString))
        Dim states As String() = queryString.Split("$")
        gvLogics.SelectedIndex = CInt(states(0))
        gvLogics.PageIndex = CInt(states(1))
        If Not String.IsNullOrEmpty(states(2)) Then
            lstQuestions.SelectedValue = states(2)
        End If
        If states(0) < 0 Then
            AddEditVisible(True, True)
            lstQuestions.Enabled = True
        Else
            AddEditVisible(True, False)
            lstQuestions.Enabled = states(3)
        End If
        CType(_uc, ILogicUC).Logic = states(4).Split("#")(0)
        ddlCategories.Enabled = lstQuestions.Enabled
        lbutCreate.Enabled = lstQuestions.Enabled
        txtStringToSearch.Enabled = lstQuestions.Enabled
        butSearch.Enabled = lstQuestions.Enabled
        butClear.Enabled = lstQuestions.Enabled
    End Sub

    Protected Sub butPreview_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butPreview.Click
        SetPreviousPage(GetState())
        Response.Redirect("QuestionPreview.aspx?qid=" & lstQuestions.SelectedValue)
    End Sub

End Class
